package com.ada.okhttp;

import com.google.gson.Gson;
import okhttp3.*;
import org.json.JSONObject;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 * Created by ada on 2017/4/26.
 */
public class Apps {

    public static final MediaType JSONTYPE=MediaType.parse("application/json; charset=utf-8");

    public static void main(String[] args) {
        //https://oapi.dingtalk.com/robot/send?access_token=60af33ccf32c64a7465b88419b24f0383c2b3e004a054e7e071f705447e4c929
        //https://api.maotouin.com/json/companyhandler/search.htm
        CompanySo object=new CompanySo();
        object.setToken("eyJhbGciOiJIUzUxMiIsImNhbGciOiJHWklQIn0.H4sIAAAAAAAAAKtWKi5NUrJSMlTSUUqtKFCyMjQ1Mjc3NjUwM6sFAOTN3rkcAAAA.pzEPJGdD2VfKSExUwHpWUz3kWn1Q9_lpDcdeiaOMhvHW9zKcoUmq-_hOgDDyqCmLEXXTD3nsI2sjRWWkvJk5Tw");
        RequestBody requestBody = RequestBody.create(JSONTYPE, new Gson().toJson(object));


        OkHttpClient client = new OkHttpClient();


        Request request = new Request.Builder()
                .url("https://api.maotouin.com/json/companyhandler/search.htm")
                .addHeader("content-type", "application/json;charset:utf-8")
                // .post(RequestBody.create(MEDIA_TYPE_TEXT, postBody))
                .post(requestBody)
                .build();
        try {
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                String json = response.body().string();
                System.out.println(json);
                String post ="";// JSON.parseObject(json).getString("postBody");
                System.out.println("转义之前：" + post);
                System.out.println("转义之后：" + URLDecoder.decode(post));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void dd() {
        JSONObject object=new JSONObject();
        object.put("msgtype","link");
        JSONObject text=new JSONObject();
        text.put("title","这是测试");
        text.put("text","这是测试");
        text.put("messageUrl","http://www.tongnainfo.com/");
        text.put("picUrl","https://static.dingtalk.com/media/lALOB0o7K8yQzJA_144_144.png");


        object.put("link",text);
        sendMessage(object);
    }

    private static JSONObject makeText() {
        JSONObject object=new JSONObject();
        object.put("msgtype","text");
        JSONObject text=new JSONObject();
        text.put("content","这是测试");
        object.put("text",text);
        return object;
    }

    private static void sendMessage(JSONObject object) {
        RequestBody requestBody = RequestBody.create(JSONTYPE, object.toString());
        OkHttpClient client = new OkHttpClient();


        Request request = new Request.Builder()
                .url("https://oapi.dingtalk.com/robot/send?access_token=60af33ccf32c64a7465b88419b24f0383c2b3e004a054e7e071f705447e4c929")
                .addHeader("content-type", "application/json;charset:utf-8")
                // .post(RequestBody.create(MEDIA_TYPE_TEXT, postBody))
                .post(requestBody)
                .build();
        try {
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                String json = response.body().string();
                System.out.println(json);
                String post ="";// JSON.parseObject(json).getString("postBody");
                System.out.println("转义之前：" + post);
                System.out.println("转义之后：" + URLDecoder.decode(post));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * @desc:post json数据提交   Header+params+json
     */
    @SuppressWarnings("deprecation")
    public static void sendHeadersAndJSON() {

        // 表单提交 这种能满足大部分的需求
        RequestBody formBody = new FormBody.Builder()
                .add("jsonData", "{\"data\":\"121\",\"data1\":\"2232\"}")
                .add("username", "Arison+中文").add("password", "1111111")
                .build();

        String postBody = "{\"type\":\"post json提交\"}";
        String postBody2 = "{\"type2\":\"post json提交\"}";
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("http://localhost:8080/spring-mvc-showcase/api/getHeaders")
                .header("cookie", "JSESSIONID=EB36DE5E50E342D86C55DAE0CDDD4F6D")
                .addHeader("content-type", "application/json;charset:utf-8")
                .addHeader("Home", "china")// 自定义的header
                .addHeader("user-agent", "android")
                // .post(RequestBody.create(MEDIA_TYPE_TEXT, postBody))
                .post(formBody)
                // 表单提交
                .put(RequestBody.create(
                        MediaType.parse("application/json; charset=utf-8"),
                        postBody))// post json提交
                .put(RequestBody.create(
                        MediaType.parse("application/json; charset=utf-8"),
                        postBody2))// post json提交
                .build();
        try {
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                String json = response.body().string();
                System.out.println(json);
                String post ="";// JSON.parseObject(json).getString("postBody");
                System.out.println("转义之前：" + post);
                System.out.println("转义之后：" + URLDecoder.decode(post));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * @desc:发送请求头以及请求参数 Header+params
     */
    public static void sendHeadersAndParams() {
        String china_str = "";
        try {
            china_str = URLEncoder.encode("中文", "UTF-8");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        // 表单提交
        RequestBody formBody = new FormBody.Builder().add("query", "Hello")
                .add("username", "Arison").add("password", "1111111").build();
        // 第二个表单会覆盖第一个
		/*
		 * RequestBody formBody2 = new FormBody.Builder() .add("search",
		 * "Jurassic Park") .build();
		 */
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("http://localhost:8080/spring-mvc-showcase/api/getHeaders")
                .header("cookie", "JSESSIONID=EB36DE5E50E342D86C55DAE0CDDD4F6D")
                .addHeader("content-type", "text/html;charset:utf-8")
                .addHeader("Home", "china")// 自定义的header
                .addHeader("Home1", china_str)// 自定义的header 传中文
                .addHeader("user-agent", "android")
                // .post(RequestBody.create(MEDIA_TYPE_TEXT, postBody))
                .post(formBody)
                // .post(formBody2)
                .build();
        try {
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                String json = response.body().string();
                System.out.println(json);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * @desc:发送请求头
     */
    public static void sendHeaders() {
        String china_str = "";
        try {
            china_str = URLEncoder.encode("中文", "UTF-8");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("http://localhost:8080/spring-mvc-showcase/api/getHeaders")
                .header("cookie", "JSESSIONID=EB36DE5E50E342D86C55DAE0CDDD4F6D")
                .addHeader("content-type", "text/html;charset:utf-8")
                .addHeader("Home", "china")// 自定义的header
                .addHeader("Home1", china_str)// 自定义的header 传中文
                .addHeader("user-agent", "android").build();
        try {
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                String json = response.body().string();
                System.out.println(json);
                String home1 = "";
                System.out.println(URLDecoder.decode(home1, "utf-8"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * @dec 基本测试
     * @throws IOException
     */
    public static void sendBasicRequest() {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url("http://www.baidu.com")
                .build();

        try {
            Response response = client.newCall(request).execute();
            if (!response.isSuccessful()) {
                // throw new IOException("服务器端错误: " + response);
            }
            // 输入响应头
            Headers responseHeaders = response.headers();
            for (int i = 0; i < responseHeaders.size(); i++) {
                System.out.println(responseHeaders.name(i) + ": "
                        + responseHeaders.value(i));
            }
            // 输出响应实体
            // System.out.println(response.body().string());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
